package com.itheima.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("CustomInterceptor...preHandle 执行前");

        // 可以进行安全控制、权限校验等
        String requestURI = request.getRequestURI();
        System.out.println("请求路径: " + requestURI);

        // 示例：检查特定的请求头
        String userAgent = request.getHeader("User-Agent");
        System.out.println("User-Agent: " + userAgent);

        // 返回true继续执行，返回false中断请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("CustomInterceptor...postHandle 执行后");

        // 可以对模型和视图进行进一步修改
        if (modelAndView != null) {
            String viewName = modelAndView.getViewName();
            System.out.println("视图名称: " + viewName);

            // 可以添加公共模型数据
            modelAndView.addObject("interceptorMsg", "这是拦截器添加的消息");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        System.out.println("CustomInterceptor...afterCompletion 完成");

        // 可以进行资源清理、日志记录等工作
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;

        System.out.println("请求执行时间: " + executeTime + "ms");

        if (ex != null) {
            System.out.println("请求处理过程中出现异常: " + ex.getMessage());
        }
    }
}